import { Component, OnInit } from '@angular/core';
import { TeaminfoService } from '../../team/teaminfo.service';
import { WorkerService } from '../../worker/worker.service';
import { ActivatedRoute, Router } from '@angular/router';
import { CheckService } from '../check.service';
import { StorageService } from '../../../../common/storage.service';

@Component({
  selector: 'app-info-check',
  templateUrl: './info.component.html',
  styleUrls: ['./info.component.css'],
  providers: [TeaminfoService, WorkerService, CheckService],
})
export class InfoCheckComponent implements OnInit {
  colsCheck;
  checkData;
  colsWorker;
  workerData;
  workerTotalRecords;
  workerLoading;
  pageSize;
  pageNo;
  teamId = 1;
  teamInfo: any = {};
  foreman: any = {};
  displayWorkInfo = false;
  workerInfo: any = {};
  displayCheck = false;
  checkObj: any = {};
  checkStatusObj: any = {};
  approveStatus = [];
  managerPhotoPcImages = []; // 手持身份证照片
  idcardPhotoFrontImages = []; // 身份证正面
  idcardPhotoReverseImages = []; // 身份证反面
  insuranceAttachImages = []; // 保险单附件
  appStandardImages = []; // APP使用规范
  engineerStandardImages = []; // 工程部处罚规范
  productManualImages = []; // 产品套餐手册
  constructionManualImages = []; // 施工手册
  pipeCardAttachImages = []; // 管道证附件
  electricAttachImages = []; // 电工证附件
  serviceContractAttachImages = []; // 合同附件
  approveNoteError = '';
  approveResultError = '';
  constructor(private teaminfoService: TeaminfoService, private workerService: WorkerService,
    private routeInfo: ActivatedRoute, private checkService: CheckService, private router: Router,
    private storage: StorageService) {
    this.workerLoading = true;
    // 审核表头
    this.colsCheck = [
      { field: 'name', header: '审核人姓名', width: '100px', frozen: false, sortable: true },
      { field: 'telephone', header: '手机号', frozen: false, sortable: true },
      { field: 'approveTime', header: '审核时间', width: '150px', sortable: true, tem: true },
      { field: 'approveResultText', header: '审核结果', sortable: true },
      { field: 'approveNote', header: '原因', width: '80px' },
    ];
    // 工人表头
    this.colsWorker = [
      { field: 'code', header: '账号', width: '100px', frozen: false, sortable: true, tem: true },
      { field: 'name', header: '姓名', frozen: false, sortable: true },
      { field: 'address', header: '现居所在地', width: '150px', sortable: true, tem: true },
      { field: 'workType', header: '工种', sortable: true },
      { field: 'telephone', header: '手机号', sortable: true },
      { field: '', header: '在施数量', width: '80px' },
      { field: 'level', header: '级别', },
      { field: 'status', header: '状态', width: '50px', sortable: true },
    ];
    this.checkObj['approveResult'] = 'approveresult_approve';
  }
  ngOnInit() {
    // 获取路由id
    this.storage.loading();
    this.routeInfo.params.subscribe((params) => {
      this.teamId = params.id;
      // 获取施工对信息
      this.teaminfoService.getTeamInfoById(this.teamId).then(data => {
        this.teamInfo = data.data.teamInfo;
        this.foreman = data.data.foreman;
        this.imgUrlData();
        // 获取工人信息
        this.workerService.list({ constructionteamTeaminfoId: this.foreman['id'] }).then(result => {
          this.storage.loadout();
          if (result.result) {
            this.workerLoading = false;
            this.workerData = result.data.list;
            this.workerTotalRecords = result.data.totalCount;
          } else {
            this.workerLoading = false;
            this.workerData = [];
            this.workerTotalRecords = 0;
            this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
          }
        });
      });
      // 获取审核信息
      this.checkService.approveList({ teamId: this.teamId }).then(data => {
        this.storage.loadout();
        this.checkData = data.data.list;
        this.approveStatus = data.data.approveStatus;
      });
      this.storage.loadout();
    });
  }

  /**
   * 备注字段验证
   */
  approveNoteCK() {
    this.checkObj['approveNote'] = this.checkObj['approveNote'] ? this.checkObj['approveNote'].trim() : '';
    if (!this.checkObj['approveNote']) {
      this.approveNoteError = '请输入原因/备注';
    } else {
      if (this.checkObj['approveNote'].length > 100) {
        this.approveNoteError = '原因/备注100字以内';
      } else {
        this.approveNoteError = '';
      }
    }
  }

  /**
   * 是否通过验证
   */
  approveResultCK() {
    if (!this.checkObj['approveResult']) {
      this.approveResultError = '是否通过不能为空！';
    } else {
      this.approveResultError = '';
    }
  }
  /**
   * 查看员工详情
   * @param event 员工详情
   */
  showWorker(event) {
    this.displayWorkInfo = true;
    this.workerService.getWorkerInfoById(event.id).then(data => {
      this.workerInfo = data.data;
    });
  }
  /**
   * dataTable分页查询方法
   * @param event
   */
  onPage(event) {
    this.pageSize = event.rows;
    const pageTem = parseInt((event.first / event.rows).toString(), 0);
    this.pageNo = pageTem + 1;
    this.workerLoading = true;
    this.workerService.list({ constructionteamTeaminfoId: 1 }, this.pageSize, this.pageNo).then(
      data => {
        if (data.result) {
          this.workerLoading = false;
          this.workerData = data.data.list;
          this.workerTotalRecords = data.data.totalCount;
        } else {
          this.workerLoading = false;
          this.workerData = [];
          this.workerTotalRecords = 0;
          this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
        }
      }
    );
  }

  back() {
    this.router.navigate(['saas/engineer/constructionteam/check']);
  }


  /**
   * 审核确认
   */
  check() {
    let flag = true;
    if (!this.checkObj['approveResult']) {
      this.approveResultError = '是否通过不能为空！';
      flag = false;
    } else {
      this.approveResultError = '';
    }
    if (!this.checkObj['approveNote']) {
      this.approveNoteError = '请输入原因/备注';
      flag = false;
    } else {
      if (this.checkObj['approveNote'].length > 100) {
        this.approveNoteError = '请原因/备注100字以内';
        flag = false;
      } else {
        this.approveNoteError = '';
      }
    }
    if (!flag) {
      return;
    }
    // if (!this.approveNoteError ) {
    //   return;
    // }
    // if (!this.approveResultError) {
    //   return;
    // }
    this.checkObj = { ...this.checkObj, teamId: this.teamId };

    this.displayCheck = false;
    this.checkService.confirm(this.checkObj).then(
      data => {
        if (data.result) {
          this.storage.messageService.emit({ severity: 'success', detail: '操作成功！' });
          this.back();
          this.approveNoteError = '';
          this.approveResultError = '';
        } else {
          this.makesure(data);
          this.storage.messageService.emit({ severity: 'error', detail: '操作失败，请重新操作！' });
        }
      }
    );
  }
  // 点击审核校验状态
  checkStatus() {
    this.checkStatusObj = { teamId: this.teamId };
    this.checkService.confirmStatus(this.checkStatusObj).then(
      data => {
        if (data.result) {
          this.displayCheck = true;
          this.checkObj['approveNote'] = '';
          this.clearSubmitError();
        } else {
          this.errordata(data);
        }
      }
    );
  }

  /**
   * 清除错误信息
   */
  clearSubmitError() {
    this.approveNoteError = '';
    this.approveResultError = '';
  }

  /**
 * 上传图片的回显
 */
  imgUrlData() {
    // 手持身份证照片
    for (let item of this.foreman['managerPhotoPcUrls'].split(',')) {
      this['managerPhotoPcImages'] = [...this['managerPhotoPcImages'], {
        source: item, thumbnail: item,
        width: '100px', maxWidth: '800px', title: ''
      }];
    }
    // 身份证正面
    for (let item of this.foreman['idcardPhotoFrontUrls'].split(',')) {
      this['idcardPhotoFrontImages'] = [...this['idcardPhotoFrontImages'], {
        source: item, thumbnail: item,
        width: '100px', maxWidth: '800px', title: ''
      }];
    }
    // 身份证反面
    for (let item of this.foreman['idcardPhotoReverseUrls'].split(',')) {
      this['idcardPhotoReverseImages'] = [...this['idcardPhotoReverseImages'], {
        source: item, thumbnail: item,
        width: '100px', maxWidth: '800px', title: ''
      }];
    }
    // 保险单附件
    for (let item of this.foreman['insuranceAttachUrls'].split(',')) {
      this['insuranceAttachImages'] = [...this['insuranceAttachImages'], {
        source: item, thumbnail: item,
        width: '100px', maxWidth: '800px', title: ''
      }];
    }
    // 合同附件
    for (let item of this.foreman['serviceContractAttachUrls'].split(',')) {
      this['serviceContractAttachImages'] = [...this['serviceContractAttachImages'], {
        source: item, thumbnail: item,
        width: '100px', maxWidth: '800px', title: ''
      }];
    }
    // 电工证附件
    for (let item of this.foreman['electricAttachUrls'].split(',')) {
      this['electricAttachImages'] = [...this['electricAttachImages'], {
        source: item, thumbnail: item,
        width: '100px', maxWidth: '800px', title: ''
      }];
    }
    // 管道证附件
    for (let item of this.foreman['pipeCardAttachUrls'].split(',')) {
      this['pipeCardAttachImages'] = [...this['pipeCardAttachImages'], {
        source: item, thumbnail: item,
        width: '100px', maxWidth: '800px', title: ''
      }];
    }
    // 施工手册
    for (let item of this.foreman['constructionManualUrls'].split(',')) {
      this['constructionManualImages'] = [...this['constructionManualImages'], {
        source: item, thumbnail: item,
        width: '100px', maxWidth: '800px', title: ''
      }];
    }
    // 产品套餐手册
    for (let item of this.foreman['productManualUrls'].split(',')) {
      this['productManualImages'] = [...this['productManualImages'], {
        source: item, thumbnail: item,
        width: '100px', maxWidth: '800px', title: ''
      }];
    }
    // 工程部处罚规范
    for (let item of this.foreman['engineerStandardUrl'].split(',')) {
      this['engineerStandardImages'] = [...this['engineerStandardImages'], {
        source: item, thumbnail: item,
        width: '100px', maxWidth: '800px', title: ''
      }];
    }
    // APP使用规范
    for (let item of this.foreman['appStandardUrls'].split(',')) {
      this['appStandardImages'] = [...this['appStandardImages'], {
        source: item, thumbnail: item,
        width: '100px', maxWidth: '800px', title: ''
      }];
    }
  }

  makesure(data) {
    this.storage.makesureService.emit({
      message: data.msg,
      header: '提示',
      rejectVisible: false,
      acceptVisible: false,
      accept: () => {
        this.back();
      },
      reject: () => {
      }
    });
  }
  // 已审核提示
  errordata(data) {
    this.storage.makesureService.emit({
      message: data.msg,
      header: '提示',
      rejectVisible: false,
      acceptVisible: false,
      accept: () => {
        this.back();
      },
      reject: () => {
        this.back();
      }
    });
  }
}
